<?php
/**
 *	[【耐小心】安米推送(nxx_appbyme_push.{modulename})] (C)2015-2099 Powered by 耐小心.
 *	Version: 1.0
 *	Date: 2015-5-6 17:28
 */


if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

class plugin_nxx_appbyme_push {
}


class plugin_nxx_appbyme_push_forum extends plugin_nxx_appbyme_push {
	function post_checkreply_message($param) {
		global $_G;
		global $thread;
		$Cer = DISCUZ_ROOT.'/data/appbyme/upload/appbyme_apns.pem';
		if (!file_exists($Cer)) {  //判断证书是否存在。
			return '';
		}
		$deviceToken = DB::result_first("SELECT uvalue FROM ".DB::table('appbyme_user_setting')." where ukey= 'deviceToken' AND uid = ".$thread[authorid]."");
		if($_G['uid'] == $thread['authorid']){ //发帖回复同一人不推送
			return '';
		}
		if($deviceToken){ //判断devicetoken存在，执行推送
			$message = $_G['username'].lang('plugin/nxx_appbyme_push', 'reply').$thread['subject'];
			$data = array('type' => 'reply',);
            $payload['aps'] = array(
              	 'alert' => $message,
              	 'sound' => 'default',
              	 'badge' => 1,
			);
            $payload['appbymeData'] = $data;
			$payload = json_encode ($payload);
			$CerPassword = DB::result_first("SELECT cvalue FROM ".DB::table('appbyme_config')." where ckey= 'certfile_apns_passphrase'");
			$CerPassword = base64_decode($CerPassword);
			$serverUrl   = "ssl://gateway.push.apple.com:2195";
			$streamContext = stream_context_create();
			stream_context_set_option ( $streamContext, 'ssl', 'local_cert', $Cer);
			stream_context_set_option ( $streamContext, 'ssl', 'passphrase', $CerPassword);
			$apns = stream_socket_client ( $serverUrl, $error, $errorString, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $streamContext);
			$msg     = chr(0) . pack('n', 32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack('n', strlen($payload)) . $payload;
			$result  = fwrite ( $apns, $msg); 
			fclose ($apns);
		}
	}
	
}
?>